const http = require("http");
const fs = require("fs");

function getData(str){
    var arr = str.split("&");
    var obj = {};
    for(var i = 0; i<arr.length;i++){
        var childArr  = arr[i].split("=");
        obj[childArr[0]] = childArr[1];
    }
    return obj
}

http.createServer((req,res) => {
    var urlObj = new URL(req.url,"http://localhost:8081/");
    var pathName = urlObj.pathname;
    if(pathName == '/'){
        var fileContent = fs.readFileSync("./post.html");
        res.writeHead(200,{"Content-Type":"text/html;charset=utf8"})
        res.write(fileContent);
        res.end();
    }
    else if(pathName == "/save"){
        var str = "";
        req.on("data",(chunk) => {
            str += chunk
        })
        req.on("end",() => {
            var postObj = getData(str);
            userList.push(postObj);
            res.end("submit success")
        })
    }
    else if(pathName == "/getlist"){
        var userStr = JSON.stringify(userList);
        res.writeHead(200,{"Content-Type":"text/plain"});
        res.end(userStr);
    }
    
    //删除数据过程，接收请求 /del?deluser=zhangsan
    //根据username从userList里面将该条数据删除
    else if(pathName == "/del"){
        var delUser = urlObj.searchParams.get("deluser");
        for(var j = 0;j<userList.length;j++){
            if(userList[j]["userName"] == delUser){
                userList.splice(j,1);
                res.end("delete success");
                return; 
            }
        }
    }
}).listen(8081)

console.log("listen 8081")